import { ModalForm, ProFormInstance } from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { useRef } from 'react';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.RuleListItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: any) => void;
  onSubmit: (values: any) => Promise<void>;
  updateModalVisible: boolean;
  values: any;
};

const InviteFriendForm: React.FC<UpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const textRef = useRef(null);
  const handleCopy = async () => {
    if (!textRef.current) return;

    const text = textRef.current.textContent;
    try {
      // 现代 API + 旧版降级方案
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text);
      } else {
        // 旧版 execCommand 方案
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      props?.onSubmit(true);
    } catch (err) {
      props?.onSubmit(false);
    }
  };

  return (
    <ModalForm
      title="邀请好友"
      width="620px"
      formRef={formRef}
      open={props.updateModalVisible}
      onOpenChange={(val) => {
        if (!val) {
          props.onCancel();
        }
      }}
      submitter={{
        // 完全自定义按钮
        render: () => [
          <Button
            key="submit"
            type="primary"
            onClick={() => {
              handleCopy();
            }}
          >
            复制链接
          </Button>,
        ],
      }}
    >
      <>
        <div ref={textRef}>http://cps.yfbro.com/account/register?inviteId={props.values}</div>
      </>
    </ModalForm>
  );
};

export default InviteFriendForm;
